package com.gaofei.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gaofei.common.utils.JwtTokenUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : gaofee
 * @date : 10:51 2021/5/19
 * @码云地址 : https://gitee.com/itgaofee
 */
//@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String path = exchange.getRequest().getURI().getPath();
        if(path.contains("/login")){
            //放行
            return chain.filter(exchange);
        }


        // 封装错误信息
        Map<String, Object> responseData = new HashMap();
        responseData.put("code", 401);
        responseData.put("message", "非法请求");
        responseData.put("cause", "Token is null");

        HttpHeaders headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("Authorization");

        if (token == null || token.isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();



            try {
                // 将信息转换为 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] data = objectMapper.writeValueAsBytes(responseData);

                // 输出错误信息到页面
                DataBuffer buffer = response.bufferFactory().wrap(data);
//                response.setStatusCode(HttpStatus.UNAUTHORIZED);//设置前端的相应状态为401
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }

        if(token!=null){
            JwtTokenUtil util = new JwtTokenUtil();
            boolean b = util.validateToken(token);
            //防止请求篡改,验证token
            if(b){
                //放行
                return chain.filter(exchange);
            }
        }

        //
        return Mono.just(responseData);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
